package tag

import (
	"fmt"

	appErrors "BookStack/pkg/errors"
)

// ========================== 标签相关错误 ==========================
// 标签不存在错误
func TagNotFound(id interface{}) error {
	return &appErrors.AppError{
		Code:    appErrors.ErrCodeTagNotFound,
		Message: fmt.Sprintf("标签不存在: %v", id),
	}
}

// 标签名称已存在错误
func TagNameExists(name string, tagType int) error {
	var typeStr string
	if tagType == 1 {
		typeStr = "文章"
	} else if tagType == 2 {
		typeStr = "书籍"
	} else {
		typeStr = "未知类型"
	}

	return &appErrors.AppError{
		Code:    appErrors.ErrCodeTagNameExists,
		Message: fmt.Sprintf("标签名称'%s'在%s标签中已存在，请使用其他名称", name, typeStr),
		Details: map[string]interface{}{
			"name": name,
			"type": tagType,
		},
	}
}

// 标签标识已存在错误
func TagSlugExists(slug string, tagType int) error {
	var typeStr string
	if tagType == 1 {
		typeStr = "文章"
	} else if tagType == 2 {
		typeStr = "书籍"
	} else {
		typeStr = "未知类型"
	}

	return &appErrors.AppError{
		Code:    appErrors.ErrCodeTagSlugExists,
		Message: fmt.Sprintf("标签标识'%s'在%s标签中已存在，请使用其他标识", slug, typeStr),
		Details: map[string]interface{}{
			"slug": slug,
			"type": tagType,
		},
	}
}

// 标签类型无效错误
func TagTypeInvalid(tagType int) error {
	return &appErrors.AppError{
		Code:    appErrors.ErrCodeTagTypeInvalid,
		Message: "无效的标签类型",
		Details: map[string]interface{}{
			"type": tagType,
		},
	}
}

// 标签批量删除失败错误
func TagBatchDeleteFailed(ids []uint, err error) error {
	return &appErrors.AppError{
		Code:    appErrors.ErrCodeTagBatchDeleteFailed,
		Message: "标签批量删除失败",
		Details: map[string]interface{}{
			"ids":    ids,
			"reason": err.Error(),
		},
	}
}

// ========================== 通用错误 ==========================

// DatabaseError 数据库错误
func DatabaseError(err error) error {
	return &appErrors.AppError{
		Code:    appErrors.ErrCodeDatabase,
		Message: err.Error(),
	}
}

// ValidationError 数据验证错误
func ValidationError(field, message string) error {
	return &appErrors.AppError{
		Code:    appErrors.ErrCodeValidation,
		Message: fmt.Sprintf("字段 %s: %s", field, message),
	}
}

// InvalidRequestError 无效请求错误
func InvalidRequestError(message string) error {
	return &appErrors.AppError{
		Code:    appErrors.ErrCodeBadRequest,
		Message: message,
	}
}

// UnauthorizedError 未授权错误
func UnauthorizedError() error {
	return &appErrors.AppError{
		Code:    appErrors.ErrCodeUnauthorized,
		Message: "未授权访问",
	}
}

// ForbiddenError 禁止访问错误
func ForbiddenError() error {
	return &appErrors.AppError{
		Code:    appErrors.ErrCodeForbidden,
		Message: "无权限执行此操作",
	}
}

// InternalError 内部服务器错误
func InternalError(err error) error {
	return &appErrors.AppError{
		Code:    appErrors.ErrCodeInternal,
		Message: err.Error(),
	}
}

// WrapError 包装错误
func WrapError(err error) error {
	if err == nil {
		return nil
	}

	// 如果已经是AppError类型，直接返回
	if appErr, ok := err.(*appErrors.AppError); ok {
		return appErr
	}

	// 包装为内部错误
	return InternalError(err)
}
